package com.yuanfeng.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.yuanfeng.activity.dto.RedpacketSendUserDTO;
import com.yuanfeng.activity.dto.UserAvailableRedpacketQueryDTO;
import com.yuanfeng.activity.dto.UserRedIdDTO;
import com.yuanfeng.activity.dto.UserRedpacketSendDTO;
import com.yuanfeng.activity.entity.ActivityRedpacketTemplateEntity;
import com.yuanfeng.activity.mapper.ActivityRedpacketBaseMapper;
import com.yuanfeng.activity.mapper.ActivityRedpacketTemplateMapper;
import com.yuanfeng.activity.service.ActivityRedpacketTemplateService;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.util.DateUtils;
import com.yuanfeng.commoms.util.ParseTokenUtils;
import com.yuanfeng.commoms.util.RedisUtil;
import com.yuanfeng.commoms.util.ResponseResult;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.vo.activity.ActivityRedpacketTemplateVO;
import com.yuanfeng.commoms.vo.activity.YfRedpacketTemplateVO;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 */
@Service
public class ActivityRedpacketTemplateServiceImpl extends ServiceImpl<ActivityRedpacketTemplateMapper, ActivityRedpacketTemplateEntity>
    implements ActivityRedpacketTemplateService{

    @Autowired
    private ActivityRedpacketBaseMapper activityRedpacketBaseMapper;
    @Override
    public ResponseResult getList(Map<String, Object> paraMap) {
        List<Integer> id= (List<Integer>) paraMap.get("id");
        List<ActivityRedpacketTemplateVO> entityList = new ArrayList<>();
        if (id != null && id.size() > 0){
            entityList = this.baseMapper.selectNewRedpacketTem(id);
        }
        return ResponseResult.success(entityList);
    }

    @Override
    public ResponseResult selectByPage(Map<String, Object> map) {
        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + map.get("token"));
        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        IPage<ActivityRedpacketTemplateEntity> page=this.page(new Query<ActivityRedpacketTemplateEntity>().getPage(map),
                                                    new LambdaQueryWrapper<ActivityRedpacketTemplateEntity>()
                                                   .eq(ActivityRedpacketTemplateEntity::getRedpacketTType, CommonType.redpacketTType.PLUS_MEMBERSHIP.getCode())
                                                   .eq(map.containsKey("redpacketTOrderlimit")&&map.get("redpacketTOrderlimit").toString().equals("0"),ActivityRedpacketTemplateEntity::getRedpacketTOrderlimit,0)
                                                   .ne(!map.containsKey("redpacketTOrderlimit")||!map.get("redpacketTOrderlimit").toString().equals("0"),ActivityRedpacketTemplateEntity::getRedpacketTOrderlimit,0)
                                                   .orderByDesc(ActivityRedpacketTemplateEntity::getRedpacketTStartDate));
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult selectList(Map<String, Object> map) {
        boolean flag=map.containsKey("redpacketTTitle");
        if(flag){
            flag= StringUtils.isNotEmpty(map.get("redpacketTTitle").toString());
        }
        IPage<ActivityRedpacketTemplateEntity> page=this.page(new Query<ActivityRedpacketTemplateEntity>().getPage(map),
                new LambdaQueryWrapper<ActivityRedpacketTemplateEntity>()
                        .eq(null != map.get("redpacketTState") && !map.get("redpacketTState").toString().isEmpty(),ActivityRedpacketTemplateEntity::getRedpacketTState,null!=map.get("redpacketTState")?map.get("redpacketTState").toString():null)
                        .like(flag,ActivityRedpacketTemplateEntity::getRedpacketTTitle,flag?map.get("redpacketTTitle").toString():null)
//                        .ge(map.containsKey("startTime")&&!map.get("startTime").toString().equals(""),ActivityRedpacketTemplateEntity::getRedpacketTStartDate,map.get("startTime").toString())
//                        .le(!map.containsKey("finishTime")||!map.get("finishTime").toString().equals(""),ActivityRedpacketTemplateEntity::getRedpacketTEndDate,map.get("finishTime").toString())
                        .orderByDesc(ActivityRedpacketTemplateEntity::getRedpacketTStartDate));
        for (ActivityRedpacketTemplateEntity red : page.getRecords()) {
            if (red.getRedpacketUsePlatform() != null) {
                String[] strs = red.getRedpacketUsePlatform().split(",");
                List<String> stringList = Arrays.asList(strs);
                red.setUsePlatformStringList(stringList);
            }
            if (red.getRedpacketGetPlatform() != null) {
                String[] strs = red.getRedpacketGetPlatform().split(",");
                List<String> stringList = Arrays.asList(strs);
                red.setGetPlatformStringList(stringList);
            }
        }
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult available(Map<String, Object> map) {
        IPage<ActivityRedpacketTemplateEntity> page=this.baseMapper.available(new Query<ActivityRedpacketTemplateEntity>().getPage(map),
                map);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult sendUserRedpacketImport(MultipartFile file, Integer redpacketTId, String token) {
        List<UserRedpacketSendDTO> userRedpacket = Lists.newArrayList();
        List<RedpacketSendUserDTO> userInfos = Lists.newArrayList();
        //解析文件 遍历用户数据
        try {
            Workbook wookbook = new XSSFWorkbook(file.getInputStream());
            Sheet sheet = wookbook.getSheetAt(0);
            int rows = sheet.getPhysicalNumberOfRows();
            for (int i = 1; i < rows; i++) {
                Row row = sheet.getRow(i);
                RedpacketSendUserDTO userInfo = new RedpacketSendUserDTO();
                if (null == row || row.getPhysicalNumberOfCells() == 0) {
                    continue;
                }
                Cell userId = row.getCell(0);
                if(null != userId) {
                    userInfo.setUserId(getValue(userId));
                }
                Cell userMobile = row.getCell(1);
                if(null != userMobile) {
                    userInfo.setUserName(getValue(userMobile));
                }
                userInfos.add(userInfo);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }


        UserRedpacketSendDTO redpacketTemplate = this.baseMapper.selectByRedpacketTId(redpacketTId);

        Integer surplusNum = redpacketTemplate.getRedpacketTTotal() - redpacketTemplate.getRedpacketTGiveout();

        if (surplusNum.intValue() < userInfos.size()) {
            return ResponseResult.fail(BizCodeEnume.TOTAL_NUMBER_OF_RED_ENVELOPES);
        }
        List<UserRedIdDTO> userIdList = new ArrayList<>();
        for (RedpacketSendUserDTO user : userInfos) {
            UserRedpacketSendDTO newRedpacketTemplate = new UserRedpacketSendDTO();
            UserRedIdDTO pojo = new UserRedIdDTO();
            newRedpacketTemplate.setRedpacketOwnerId(user.getUserId());
            newRedpacketTemplate.setRedpacketOwnerName(user.getUserName());

            newRedpacketTemplate.setRedpacketTId(redpacketTemplate.getRedpacketTId());
            newRedpacketTemplate.setRedpacketTTitle(redpacketTemplate.getRedpacketTTitle());
            newRedpacketTemplate.setRedpacketTDesc(redpacketTemplate.getRedpacketTDesc());
            newRedpacketTemplate.setRedpacketTStartDate(redpacketTemplate.getRedpacketTStartDate());
            newRedpacketTemplate.setRedpacketTEndDate(redpacketTemplate.getRedpacketTEndDate());
            newRedpacketTemplate.setRedpacketActiveDate(redpacketTemplate.getRedpacketActiveDate());
            newRedpacketTemplate.setRedpacketTPrice(redpacketTemplate.getRedpacketTPrice());
            newRedpacketTemplate.setRedpacketTOrderlimit(redpacketTemplate.getRedpacketTOrderlimit());
            newRedpacketTemplate.setRedpacketState(redpacketTemplate.getRedpacketState());
            newRedpacketTemplate.setRedpacketTTotal(redpacketTemplate.getRedpacketTTotal());
            newRedpacketTemplate.setRedpacketTGiveout(redpacketTemplate.getRedpacketTGiveout());
            newRedpacketTemplate.setRedpacketType(redpacketTemplate.getRedpacketType());
            newRedpacketTemplate.setShopLimit(redpacketTemplate.getShopLimit());
            newRedpacketTemplate.setGoodsCatLimit(redpacketTemplate.getGoodsCatLimit());

            newRedpacketTemplate.setRedpacketType(6);
            newRedpacketTemplate.setRedpacketState(1);
            newRedpacketTemplate.setRedpacketActiveDate(new Date());

            userRedpacket.add(newRedpacketTemplate);

            pojo.setUserId(String.valueOf(user.getUserId()));
            pojo.setRedpacketTPrice(String.valueOf(redpacketTemplate.getRedpacketTPrice()));
            userIdList.add(pojo);
        }

        activityRedpacketBaseMapper.updateUserRedpacketBatch(userRedpacket);
        this.baseMapper.updateRedpacketTGiveout(userInfos.size());
        return ResponseResult.fail(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult sending(UserRedpacketSendDTO param) {
        Integer redpacketTId = param.getRedpacketTId();
        //要赠送的用户信息
        List<RedpacketSendUserDTO> userInfos = param.getUserInfos();

        List<UserRedpacketSendDTO> userRedpacket = Lists.newArrayList();
        //查询红包信息
        UserRedpacketSendDTO redpacketTemplate = this.baseMapper.selectByRedpacketTId(redpacketTId);
        //计算剩余红包数
        Integer surplusNum = redpacketTemplate.getRedpacketTTotal() - redpacketTemplate.getRedpacketTGiveout();

        if (surplusNum.intValue() < userInfos.size()) {
            return ResponseResult.fail(BizCodeEnume.TOTAL_NUMBER_OF_RED_ENVELOPES);
        }

        List<UserRedIdDTO> userIdList = new ArrayList<>();
        //封装数据赠送红包
        for (RedpacketSendUserDTO user : userInfos) {
            UserRedIdDTO pojo = new UserRedIdDTO();
            UserRedpacketSendDTO newRedpacketTemplate = new UserRedpacketSendDTO();

            newRedpacketTemplate.setRedpacketOwnerId(user.getUserId());
            newRedpacketTemplate.setRedpacketOwnerName(user.getUserName());

            newRedpacketTemplate.setRedpacketTId(redpacketTemplate.getRedpacketTId());
            newRedpacketTemplate.setRedpacketTTitle(redpacketTemplate.getRedpacketTTitle());
            newRedpacketTemplate.setRedpacketTDesc(redpacketTemplate.getRedpacketTDesc());
            newRedpacketTemplate.setRedpacketTStartDate(redpacketTemplate.getRedpacketTStartDate());
            newRedpacketTemplate.setRedpacketTEndDate(redpacketTemplate.getRedpacketTEndDate());
            newRedpacketTemplate.setRedpacketActiveDate(redpacketTemplate.getRedpacketActiveDate());
            newRedpacketTemplate.setRedpacketTPrice(redpacketTemplate.getRedpacketTPrice());
            newRedpacketTemplate.setRedpacketTOrderlimit(redpacketTemplate.getRedpacketTOrderlimit());
            newRedpacketTemplate.setRedpacketState(redpacketTemplate.getRedpacketState());
            newRedpacketTemplate.setRedpacketTTotal(redpacketTemplate.getRedpacketTTotal());
            newRedpacketTemplate.setRedpacketTGiveout(redpacketTemplate.getRedpacketTGiveout());
            newRedpacketTemplate.setRedpacketType(redpacketTemplate.getRedpacketType());
            newRedpacketTemplate.setShopLimit(redpacketTemplate.getShopLimit());
            newRedpacketTemplate.setGoodsCatLimit(redpacketTemplate.getGoodsCatLimit());
            newRedpacketTemplate.setRedpacketFrom(redpacketTemplate.getRedpacketFrom());

            newRedpacketTemplate.setRedpacketType(6);
            newRedpacketTemplate.setRedpacketState(1);
            newRedpacketTemplate.setRedpacketActiveDate(new Date());
            userRedpacket.add(newRedpacketTemplate);

            pojo.setUserId(String.valueOf(user.getUserId()));
            pojo.setRedpacketTPrice(String.valueOf(redpacketTemplate.getRedpacketTPrice()));
            userIdList.add(pojo);

        }

        activityRedpacketBaseMapper.updateUserRedpacketBatch(userRedpacket);
        this.baseMapper.updateRedpacketTGiveout(userInfos.size());
        return ResponseResult.fail(BizCodeEnume.OPERATION_SUCCESSFUL);

    }

    @Override
    public ResponseResult giveList() {
        List<ActivityRedpacketTemplateEntity> list=this.baseMapper.giveList();
        return ResponseResult.success(list);
    }

    @Override
    public ResponseResult updateRedpacketTemp(Map<String, Object> paraMap) {
        Integer redpacketCount =this.baseMapper.selectById(String.valueOf(paraMap.get("redpacketTId"))).getRedpacketTTotal();
        if (null != paraMap.get("addRedCount") && !("".equals(paraMap.get("addRedCount")))) {
            Integer redpacketTTotal = redpacketCount + Integer.parseInt(String.valueOf(paraMap.get("addRedCount")));
            paraMap.put("redpacketTTotal", redpacketTTotal);
        }
        Integer torf = this.baseMapper.updateRedpacketTemp(paraMap);
        //修改用户领到手的红包状态
        //查询当前红包是否在 有效期区间内
        Integer start = this.baseMapper.selectRedpacketTime(paraMap);
        if(null != start && start > 0){
            //红包在有效期内才可以修改用户领到手的 红包状态
            if(null != paraMap.get("redpacketTState")) {
                // 修改用户到手的红包状态
                activityRedpacketBaseMapper.updateRedpacketUserStart(paraMap);
            }
        }
        if (1 == torf) {
            return ResponseResult.fail(BizCodeEnume.OPERATION_SUCCESSFUL);
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult insertRedpacketTemp(Map<String, String> paraMap) throws IOException {
        // 红包面额
        Double redpacketTPrice = Double.parseDouble(paraMap.get("redpacketTPrice"));
        // 订单限额
        Double redpacketTOrderlimit = Double.parseDouble(paraMap.get("redpacketTOrderlimit"));
        String token = paraMap.get("token");
        UserInfoVO ui = ParseTokenUtils.getPlatformUser(token);
        SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String finishTime = dateformat.format(new Date());

        String userRealname = ui.getUserRealname();
        paraMap.put("orderOperator", userRealname);
        paraMap.put("orderOperatorTime", finishTime);
        if (redpacketTOrderlimit != 0){
            if (redpacketTOrderlimit < redpacketTPrice) {
                return ResponseResult.fail(BizCodeEnume.ORDER_LIMIT_CANNOT_BE_LESS);
            }
        }
        if (null == paraMap.get("redpacketUsePlatform") || "".equals(paraMap.get("redpacketUsePlatform"))) {
            paraMap.put("redpacketUsePlatform", "0");
        }
        if (null == paraMap.get("redpacketGetPlatform") || "".equals(paraMap.get("redpacketGetPlatform"))) {
            paraMap.put("redpacketGetPlatform", "0");
        }
        //plus会员
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        Date date = new Date();
        if (paraMap.get("redpacketTType").equals("7")){
            paraMap.put("redpacketTStartDate",format.format(date));
            paraMap.put("shopLimit","1");
            paraMap.put("frontEndIsDisplay","1");
            paraMap.put("redpacketIsBooking","1");
            paraMap.put("redpacketTEachlimit","0");
            paraMap.put("redpacketTTotal","0");
            paraMap.put("redpacketUsePlatform","0");
            paraMap.put("redpacketTGiveout","0");
            paraMap.put("redpacketTEndDate",null);
            paraMap.put("robRedpacketStartDate",null);
            paraMap.put("robRedpacketEndDate",null);
        }
        Integer torf = this.baseMapper.insertRedpacketTemp(paraMap);
        if (1 == torf) {
            return ResponseResult.success();
        }
        return ResponseResult.fail(BizCodeEnume.OPERATION_FAILED);
    }

    @Override
    public ResponseResult getRedpacketDetail(Map<String, Object> paraMap) {
        ActivityRedpacketTemplateEntity entity=this.baseMapper.selectById(paraMap.get("redpacketTId").toString());
        return ResponseResult.success(entity);
    }

    private static String getValue(Cell xSSFCell) {
        if (null == xSSFCell) {
            return "";
        }
        String cellValue = "";
        // 以下是判断数据的类型
        switch (xSSFCell.getCellType()) {
            // 数字
            case HSSFCell.CELL_TYPE_NUMERIC:
                xSSFCell.setCellType(Cell.CELL_TYPE_STRING);
                cellValue = xSSFCell.getStringCellValue();
                break;
            // 字符串
            case HSSFCell.CELL_TYPE_STRING:
                cellValue = xSSFCell.getStringCellValue();
                break;
            // Boolean
            case HSSFCell.CELL_TYPE_BOOLEAN:
                cellValue = xSSFCell.getBooleanCellValue() + "";
                break;
            // 公式
            case HSSFCell.CELL_TYPE_FORMULA:
                cellValue = xSSFCell.getCellFormula() + "";
                break;
            // 空值
            case HSSFCell.CELL_TYPE_BLANK:
                cellValue = "";
                break;
            // 故障
            case HSSFCell.CELL_TYPE_ERROR:
                cellValue = "";
                break;
            default:
                cellValue = "";
                break;
        }
        return cellValue;
    }
    @Override
    public ResponseResult queryBookingRpList(UserAvailableRedpacketQueryDTO param) {
        List<YfRedpacketTemplateVO> bookingRpList = this.baseMapper.selectBookingRpList();

        if (null == bookingRpList) {
            return ResponseResult.success("无倒计时红包");
        }

        for (YfRedpacketTemplateVO bookingRp : bookingRpList) {
            BigDecimal redPackageGetProgress = new BigDecimal(bookingRp.getRedpacketTGiveout())
                    .divide(new BigDecimal(bookingRp.getRedpacketTTotal()), 2, BigDecimal.ROUND_HALF_UP);

            bookingRp.setRedPackageGetProgress(redPackageGetProgress);

            if (DateUtils.compareDate2(bookingRp.getRedpacketTStartDate())) {
                bookingRp.setOverplusTime(DateUtils.getOverplusTime(new Date(), bookingRp.getRedpacketTStartDate()));
                bookingRp.setReceiveOrNot(CommonType.PromotionReceiveOrNot.BOOKING.getCode());

            } else {

                if (bookingRp.getRedpacketTGiveout().intValue() >= bookingRp.getRedpacketTTotal().intValue()) {
                    bookingRp.setReceiveOrNot(CommonType.PromotionReceiveOrNot.NO_NUM_GET.getCode());
                } else {

                    // 获取用户信息
                    String token = param.getToken();
                    UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(token);
                    if (null != userInfo) {
                        param.setRedpacketOwnerId(userInfo.getUserId());
                    } else {
                        return ResponseResult.success(bookingRpList);
                    }
                    param.setRedpacketTId(bookingRp.getRedpacketTId());
                    Integer redpacketState = activityRedpacketBaseMapper.checkReceivedRpOrNot4(param);
                    // ReceiveOrNot:0未领取1已领取2不可领取3已用4过期
                    if (null == redpacketState) {
                        bookingRp.setReceiveOrNot(0);
                    } else {
                        bookingRp.setReceiveOrNot(1);
                    }
                }
            }
        }
        return ResponseResult.success(bookingRpList);
    }
}




